package com.xiaozhi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xiaozhi.common.Result;
import com.xiaozhi.dto.AnalysisRequestDto;
import com.xiaozhi.entity.HealthAnalytics;
import com.xiaozhi.service.HealthAnalyticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 健康数据分析控制器
 *
 * @author xiaozhi
 * @since 2024-01-15
 */
@RestController
@RequestMapping("/api/health-analytics")
@Tag(name = "健康数据分析", description = "健康数据分析相关接口")
@CrossOrigin(origins = "*")
public class HealthAnalyticsController {

    private static final Logger log = LoggerFactory.getLogger(HealthAnalyticsController.class);

    @Autowired
    private HealthAnalyticsService healthAnalyticsService;

    @PostMapping("/generate")
    @Operation(summary = "生成健康分析", description = "为指定用户生成健康数据分析")
    public Result<HealthAnalytics> generateAnalysis(
            @Parameter(description = "健康分析请求参数") @RequestBody AnalysisRequestDto request) {
        
        // TODO: 从JWT token中获取用户ID，这里暂时使用传入的userId
        log.info("生成健康分析请求，用户ID: {}, 分析类型: {}", request.getUserId(), request.getAnalysisType());
        
        HealthAnalytics analytics = healthAnalyticsService.generateHealthAnalysis(
                request.getUserId(), 
                request.getAnalysisType(), 
                request.getStartDate(), 
                request.getEndDate());
        return Result.success("健康分析生成成功", analytics);
    }

    @PostMapping("/vital-signs")
    @Operation(summary = "生成生命体征分析", description = "生成用户生命体征数据分析")
    public Result<HealthAnalytics> generateVitalSignsAnalysis(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("生成生命体征分析请求，用户ID: {}", userId);
        
        HealthAnalytics analytics = healthAnalyticsService.generateVitalSignsAnalysis(userId, startDate, endDate);
        return Result.success("生命体征分析生成成功", analytics);
    }

    @PostMapping("/health-trend")
    @Operation(summary = "生成健康趋势分析", description = "生成用户健康趋势数据分析")
    public Result<HealthAnalytics> generateHealthTrendAnalysis(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("生成健康趋势分析请求，用户ID: {}", userId);
        
        HealthAnalytics analytics = healthAnalyticsService.generateHealthTrendAnalysis(userId, startDate, endDate);
        return Result.success("健康趋势分析生成成功", analytics);
    }

    @PostMapping("/risk-assessment")
    @Operation(summary = "生成风险评估", description = "生成用户健康风险评估")
    public Result<HealthAnalytics> generateRiskAssessment(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("生成风险评估请求，用户ID: {}", userId);
        
        HealthAnalytics analytics = healthAnalyticsService.generateRiskAssessment(userId, startDate, endDate);
        return Result.success("风险评估生成成功", analytics);
    }

    @PostMapping("/symptom-pattern")
    @Operation(summary = "生成症状模式分析", description = "生成用户症状模式分析")
    public Result<HealthAnalytics> generateSymptomPatternAnalysis(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("生成症状模式分析请求，用户ID: {}", userId);
        
        HealthAnalytics analytics = healthAnalyticsService.generateSymptomPatternAnalysis(userId, startDate, endDate);
        return Result.success("症状模式分析生成成功", analytics);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户分析记录", description = "分页获取指定用户的健康分析记录")
    public Result<IPage<HealthAnalytics>> getUserAnalytics(
            @Parameter(description = "用户ID") @PathVariable("userId") Long userId,
            @Parameter(description = "页码") @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        
        log.info("获取用户分析记录，用户ID: {}, 页码: {}, 页大小: {}", userId, pageNum, pageSize);
        
        IPage<HealthAnalytics> page = healthAnalyticsService.getAnalyticsByUserId(userId, pageNum, pageSize);
        return Result.success("获取用户分析记录成功", page);
    }

    @GetMapping("/user/{userId}/type/{analysisType}")
    @Operation(summary = "按类型获取分析记录", description = "获取指定用户和分析类型的健康分析记录")
    public Result<List<HealthAnalytics>> getAnalyticsByType(
            @Parameter(description = "用户ID") @PathVariable("userId") Long userId,
            @Parameter(description = "分析类型") @PathVariable("analysisType") String analysisType) {
        
        log.info("按类型获取分析记录，用户ID: {}, 分析类型: {}", userId, analysisType);
        
        List<HealthAnalytics> analytics = healthAnalyticsService.getAnalyticsByType(userId, analysisType);
        return Result.success("获取分析记录成功", analytics);
    }

    @GetMapping("/user/{userId}/recent")
    @Operation(summary = "获取最近分析记录", description = "获取指定用户最近的健康分析记录")
    public Result<List<HealthAnalytics>> getRecentAnalytics(
            @Parameter(description = "用户ID") @PathVariable("userId") Long userId,
            @Parameter(description = "记录数量") @RequestParam(name = "limit", defaultValue = "5") Integer limit) {
        
        log.info("获取最近分析记录，用户ID: {}, 数量: {}", userId, limit);
        
        List<HealthAnalytics> analytics = healthAnalyticsService.getRecentAnalytics(userId, limit);
        return Result.success("获取最近分析记录成功", analytics);
    }

    @GetMapping("/user/{userId}/health-score-trend")
    @Operation(summary = "获取健康评分趋势", description = "获取指定用户的健康评分趋势数据")
    public Result<List<Map<String, Object>>> getHealthScoreTrend(
            @Parameter(description = "用户ID") @PathVariable("userId") Long userId,
            @Parameter(description = "开始日期") @RequestParam(name = "startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam(name = "endDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("获取健康评分趋势，用户ID: {}", userId);
        
        List<Map<String, Object>> trendData = healthAnalyticsService.getHealthScoreTrend(userId, startDate, endDate);
        return Result.success("获取健康评分趋势成功", trendData);
    }

    @GetMapping("/user/{userId}/statistics")
    @Operation(summary = "获取健康统计数据", description = "获取指定用户的健康统计数据")
    public Result<Map<String, Object>> getHealthStatistics(
            @Parameter(description = "用户ID") @PathVariable(name = "userId") Long userId) {
        
        log.info("获取健康统计数据，用户ID: {}", userId);
        
        Map<String, Object> statistics = healthAnalyticsService.getHealthStatistics(userId);
        return Result.success("获取健康统计数据成功", statistics);
    }

    @GetMapping("/user/{userId}/unread-high-risk")
    @Operation(summary = "获取未读高风险分析", description = "获取指定用户未读的高风险健康分析")
    public Result<List<HealthAnalytics>> getUnreadHighRiskAnalytics(
            @Parameter(description = "用户ID") @PathVariable("userId") Long userId) {
        
        log.info("获取未读高风险分析，用户ID: {}", userId);
        
        List<HealthAnalytics> analytics = healthAnalyticsService.getUnreadHighRiskAnalytics(userId);
        return Result.success("获取未读高风险分析成功", analytics);
    }

    @PutMapping("/{analyticsId}/mark-read")
    @Operation(summary = "标记为已读", description = "将指定的健康分析标记为已读")
    public Result<Void> markAsRead(
            @Parameter(description = "分析ID") @PathVariable("analyticsId") Long analyticsId) {
        
        log.info("标记分析为已读，分析ID: {}", analyticsId);
        
        boolean success = healthAnalyticsService.markAsRead(analyticsId);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("标记为已读失败");
        }
    }

    @PutMapping("/batch-mark-read")
    @Operation(summary = "批量标记为已读", description = "批量将健康分析标记为已读")
    public Result<Void> batchMarkAsRead(
            @Parameter(description = "分析ID列表") @RequestBody List<Long> analyticsIds) {
        
        log.info("批量标记分析为已读，数量: {}", analyticsIds.size());
        
        boolean success = healthAnalyticsService.batchMarkAsRead(analyticsIds);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("批量标记为已读失败");
        }
    }

    @DeleteMapping("/{analyticsId}")
    @Operation(summary = "删除分析记录", description = "删除指定的健康分析记录")
    public Result<Void> deleteAnalytics(
            @Parameter(description = "分析ID") @PathVariable Long analyticsId,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        
        log.info("删除分析记录，分析ID: {}, 用户ID: {}", analyticsId, userId);
        
        boolean success = healthAnalyticsService.deleteAnalytics(analyticsId, userId);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("删除分析记录失败");
        }
    }

    @GetMapping("/user/{userId}/latest-by-type")
    @Operation(summary = "获取各类型最新分析", description = "获取指定用户各分析类型的最新记录")
    public Result<List<HealthAnalytics>> getLatestAnalyticsByType(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        
        log.info("获取各类型最新分析，用户ID: {}", userId);
        
        List<HealthAnalytics> analytics = healthAnalyticsService.getLatestAnalyticsByType(userId);
        return Result.success("获取各类型最新分析成功", analytics);
    }

    @GetMapping("/user/{userId}/monthly-summary")
    @Operation(summary = "获取月度汇总", description = "获取指定用户指定月份的健康分析汇总")
    public Result<Map<String, Object>> getMonthlySummary(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "年份") @RequestParam Integer year,
            @Parameter(description = "月份") @RequestParam Integer month) {
        
        log.info("获取月度汇总，用户ID: {}, 年月: {}-{}", userId, year, month);
        
        Map<String, Object> summary = healthAnalyticsService.getMonthlySummary(userId, year, month);
        return Result.success("获取月度汇总成功", summary);
    }

    @GetMapping("/user/{userId}/improvement-trend")
    @Operation(summary = "获取改善趋势", description = "获取指定用户的健康改善趋势数据")
    public Result<Map<String, Object>> getImprovementTrend(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("获取改善趋势，用户ID: {}", userId);
        
        Map<String, Object> trend = healthAnalyticsService.getImprovementTrend(userId, startDate, endDate);
        return Result.success("获取改善趋势成功", trend);
    }

    @PostMapping("/calculate-health-score")
    @Operation(summary = "计算健康评分", description = "计算指定用户在指定时间范围内的健康评分")
    public Result<Integer> calculateHealthScore(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        log.info("计算健康评分，用户ID: {}", userId);
        
        Integer healthScore = healthAnalyticsService.calculateHealthScore(userId, startDate, endDate);
        return Result.success("计算健康评分成功", healthScore);
    }

    @GetMapping("/system/stats")
    @Operation(summary = "获取系统健康统计", description = "获取系统级别的健康数据统计")
    public Result<Map<String, Object>> getSystemHealthStats() {
        
        log.info("获取系统健康统计");
        
        Map<String, Object> stats = healthAnalyticsService.getSystemHealthStats();
        return Result.success("获取系统健康统计成功", stats);
    }

    @DeleteMapping("/cleanup")
    @Operation(summary = "清理过期记录", description = "清理指定天数之前的过期健康分析记录")
    public Result<Integer> cleanupExpiredRecords(
            @Parameter(description = "保留天数") @RequestParam(name = "daysToKeep", defaultValue = "90") Integer daysToKeep) {
        
        log.info("清理过期记录，保留天数: {}", daysToKeep);
        
        int deletedCount = healthAnalyticsService.cleanupExpiredRecords(daysToKeep);
        return Result.success("清理过期记录成功", deletedCount);
    }
}